# Definition for singly-linked list.
from typing import Optional
from DataStructure import NodesFromList, ListNode
class Solution:
    def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
        queue = [head]
        tmp = head
        while tmp.next is not None:
            tmp = tmp.next
            while len(queue) > 0 and tmp.val > queue[-1].val:
                queue.pop()
            queue.append(tmp)
        res = queue[0]
        if len(queue) > 0:
            for i in range(len(queue)-1):
                queue[i].next = queue[i+1]
        return res

if __name__ == '__main__':
    head = [5,2,13,3,8]
    h = NodesFromList(head)
    s = Solution()
    res = s.removeNodes(h)
    print(res.toList())